package com.example.membersteward.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.membersteward.common.CommonResult;
import com.example.membersteward.entity.Menu;
import com.example.membersteward.exception.ServiceException;
import com.example.membersteward.service.MenuService;
import com.example.membersteward.mapper.MenuMapper;
import com.example.membersteward.util.BaseUtils;
import com.example.membersteward.util.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author 26690
 * @description 针对表【menu(菜单表)】的数据库操作Service实现
 * @createDate 2025-04-08 22:52:37
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu>
        implements MenuService {
    private static final Logger logger = LoggerFactory.getLogger(MenuServiceImpl.class);
    @Resource
    MenuMapper menuMapper;

    @Override
    public CommonResult getMenu() {
        try {
            Long userId = SecurityUtils.getUserId();
            List<Map<String, Object>> results = menuMapper.selectByUserId(userId);
            // 用于存储最终的菜单列表
            List<Map<String, Object>> menuList = dealMenu(results);

            return CommonResult.success(menuList);
        } catch (ServiceException e) {
            return CommonResult.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("服务执行异常", e);
            return CommonResult.error("服务执行异常");
        }
    }

    @Override
    public CommonResult getAllMenu() {
        try {
            List<Map<String, Object>> results = menuMapper.selectAllMenu();
            // 用于存储最终的菜单列表
            List<Map<String, Object>> menuList = dealMenu(results);
            return CommonResult.success(menuList);
        } catch (Exception e) {
            logger.error("服务执行异常", e);
            return CommonResult.error("服务执行异常");
        }
    }

    @Override
    public CommonResult deleteMenu(Long menuId) {
        if (BaseUtils.isNull(menuId)) {
            return CommonResult.error("请检查输入内容");
        }
        try {
            int ret = menuMapper.deleteByMenuId(menuId);
            if (ret <= 0) {
                return CommonResult.error("数据库执行异常");
            }
            return CommonResult.success("删除成功");
        } catch (Exception e) {
            logger.error("执行异常！", e);
            return CommonResult.error("数据库执行异常");
        }
    }

    @Override
    public CommonResult insertMenu(Menu menu) {
        if (BaseUtils.isNull(menu)) {
            return CommonResult.error("请检查上送内容");
        }
        try {
            menu.setCreateTime(new Date());
            int ret = menuMapper.insertMenu(menu);
            if (ret <= 0) {
                return CommonResult.error("数据库执行异常");
            }
            return CommonResult.success("新增成功");
        } catch (Exception e) {
            logger.error("执行异常！", e);
            return CommonResult.error("数据库执行异常");
        }
    }

    @Override
    public CommonResult updateMenu(Menu menu) {
        if (BaseUtils.isNull(menu)) {
            return CommonResult.error("请检查上送内容");
        }
        try {
            int ret = menuMapper.updateMenu(menu);
            if (ret <= 0) {
                return CommonResult.error("数据库执行异常");
            }
            return CommonResult.success("修改成功");
        } catch (Exception e) {
            logger.error("执行异常！", e);
            return CommonResult.error("数据库执行异常");
        }
    }

    @Override
    public CommonResult getMenuById(Long menuId) {
        if (BaseUtils.isNull(menuId)) {
            return CommonResult.error("请检查输入内容");
        }
        try {
            Menu menu = menuMapper.selectByMenuId(menuId);
            return CommonResult.success(menu);
        }catch (Exception e) {
            logger.error("执行异常！", e);
            return CommonResult.error("数据库执行异常");
        }
    }

    /**
     * 处理父子菜单，返回数据
     *
     * @param results 查询到的父子菜单数据
     * @return 返回处理后的数据
     */
    public List<Map<String, Object>> dealMenu(List<Map<String, Object>> results) {
        // 用于存储最终的菜单列表
        List<Map<String, Object>> menuList = new ArrayList<>();
        // 用于快速查找父菜单
        Map<String, Map<String, Object>> menuMap = new HashMap<>();

        // 第一次遍历，处理顶级菜单
        for (Map<String, Object> row : results) {
            String parentId = String.valueOf(row.get("parent_menu_id"));
            if (!menuMap.containsKey(parentId)) {
                Map<String, Object> parentMenu = new HashMap<>();
                parentMenu.put("menuId", parentId);
                parentMenu.put("parentId", "0");
                parentMenu.put("menuName", row.get("parent_menu_name"));
                parentMenu.put("type", row.get("parent_type"));
                parentMenu.put("routerPath", row.get("parent_router_path"));
                parentMenu.put("componentsPath", row.get("parent_components_path"));
                parentMenu.put("displayOrder", row.get("parent_display_order"));
                parentMenu.put("menuIcon", row.get("parent_menu_icon"));
                parentMenu.put("visible", row.get("parent_visible"));
                String childId = BaseUtils.valueOf(row.get("child_menu_id"));
                if (childId != null) {
                    parentMenu.put("children", new ArrayList<Map<String, Object>>());
                }
                menuMap.put(parentId, parentMenu);
                menuList.add(parentMenu);
            }
            String childId = BaseUtils.valueOf(row.get("child_menu_id"));
            if (childId != null) {
                Map<String, Object> parentMenu = menuMap.get(parentId);
                if (parentMenu != null) {
                    Map<String, Object> childMenu = new HashMap<>();
                    childMenu.put("menuId", childId);
                    childMenu.put("parentId", parentId);
                    childMenu.put("menuName", row.get("child_menu_name"));
                    childMenu.put("type", row.get("child_type"));
                    childMenu.put("routerPath", row.get("child_router_path"));
                    childMenu.put("componentsPath", row.get("child_components_path"));
                    childMenu.put("displayOrder", row.get("child_display_order"));
                    childMenu.put("menuIcon", row.get("child_menu_icon"));
                    childMenu.put("visible", row.get("child_visible"));
                    ((List<Map<String, Object>>) parentMenu.get("children")).add(childMenu);
                }
            }
        }
        return menuList;
    }
}




